import {DEVICE_CLOSE_EDIT, DEVICE_OPEN_EDIT, DEVICE_QUERY_CHANGE, QUERY,} from '../types/DeviceType'
import {deleteDeviceService, queryDeviceService, saveDeviceService} from "../service/Device";

const queryAction = (param) => {
  return (dispatch) => {
    queryDeviceService(param).then(res => {
      dispatch(query(res.data));
    }).catch(err => {
      alert(err)
    })
  }
}

const query = (data) => {
  return {
    type: QUERY,
    payload: {
      record: data.data.records.map(it => {
        it.key = it.id;
        return it
      }),
      page: {
        total: data.data.total,
        size: data.data.size,
        current: data.data.current,
        pages: data.data.pages
      }
    }
  }
}

const deleteDeviceAction = (id) => {
  return (dispatch) => {
    deleteDeviceService(id)
      .then(it => it.status === 200)
      .catch(err => {
        alert(err)
      })
      .then(() => dispatch(queryAction({})))
  }
}

const addDeviceAction = (record) => {
  return (dispatch) => {
    saveDeviceService(record).then(it => {
      dispatch(closeEditAction())
      dispatch(queryAction({}))
    }).catch(err => {
      alert(err)
    })
  }

}

const closeEditAction = () => {
  return {
    type: DEVICE_CLOSE_EDIT
  }
}

const openEditAction = (record) => {
  return {
    type: DEVICE_OPEN_EDIT,
    payload: record,
  }
}

export {
  queryAction,
  deleteDeviceAction,
  addDeviceAction,
  closeEditAction,
  openEditAction,
}